/*
accesskey.js

This software is provided as-is. You may use it for commercial or 
personal use. If you distribute it, please keep this notice intact.
Copyright (c) 2005 Hirotaka Ogawa

SEE ALSO
http://as-is.net/blog/archives/000982.html
*/

function AccessKey(tname, cname) {
	this.tag_open = '<em>';
	this.tag_close = '</em>';

	AccessKey.prototype._init = function(tname, cname) {
		if (tname) {
			this.tag_open = cname ?
				'<' + tname + ' class="' + cname + '">' : 
				'<' + tname + '>';
			this.tag_close = '</' + tname + '>';
		}
	}

	AccessKey.prototype.convertString = function(str, key) {
		var pos = str.indexOf(key);
		if (pos < 0) return;
		var len = str.length;
		key = this.tag_open + key + this.tag_close;
		if (pos == 0)
			return key + str.substr(pos + 1, len);
		else if (pos == len - 1)
			return str.substr(0, pos - 1) + key;
		else
			return str.substr(0, pos) + key + str.substr(pos + 1, len);
	}

	AccessKey.prototype.convertElement = function(ele) {
		var text = ele.innerHTML;
		var key = ele.accessKey.toUpperCase();
		if (text && key) {
			var modifiedText = this.convertString(text, key);
			if (!modifiedText)
				modifiedText = this.convertString(text, key.toLowerCase());
			if (modifiedText)
				ele.innerHTML = modifiedText;
			else
				ele.innerHTML += ' (' + this.tag_open + key + this.tag_close + ')';
		}
	}

	this._init(tname, cname);
}

function modifyAccessKey(tname, cname) {
	var o = new AccessKey(tname, cname);
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		o.convertElement(labels[i]);
	}
}
modifyAccessKey();
